// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.dfa.matchtables;

import java.io.PrintStream;

/**
 * Utility class to help print progress of match table generation.
 *
 * @author Moshe Kahan
 */
public class Progress {

  static void printProgress(MatchTable ... tables) {
    printProgress(System.out, tables);
  }

  static void printProgress(PrintStream printStream, MatchTable ... tables) {
    boolean moreThanOne = false;
    for (MatchTable table : tables) {
      if (table != null) {
        if (moreThanOne) {
          printStream.print(", ");
        } else {
          System.out.print("Generating rows for ");
        }
        printStream.print(table.getName());
        moreThanOne = true;
      }
    }
    if (moreThanOne) {
      printStream.println(" match table(s)");
    }
  }

  Progress() {
    stepsTaken = 0;
    stepsTotal = 0;
    dirtyOutput = false;
  }

  void start(int stepsTotal) {
    stepsTaken = 0;
    this.stepsTotal = stepsTotal;
  }

  synchronized void next() {
    dirtyOutput = true;
    double stepPercent = 100.0f * ++stepsTaken / stepsTotal;
    System.out.printf("\r[%.1f%% completed]", stepPercent);
  }

  void end() {
    stepsTaken = 0;
    stepsTotal = 0;
    if (dirtyOutput) {
      System.out.println();
    }
  }

  private int stepsTaken;
  private int stepsTotal;
  private boolean dirtyOutput;
}
